package com.chefu.common.exception.controller;


import com.chefu.common.exception.CfException;
import com.chefu.common.exception.ExceptionEnum;
import com.chefu.common.exception.ExceptionResult;
import com.chefu.common.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class CfExceptionController {

    /**
     * 异常处理方法
     */
    @ExceptionHandler(value = CfException.class)   // 这个方法用于捕获CfException异常类型 注意：@ExceptionHandler捕获的异常类必须是RuntimeExxception或者Exception
    @ResponseBody  // 返回值转换为Json字符串
    public R handlerException(CfException e){
        return R.error(new ExceptionResult(e));
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现异常{}，异常的类型是{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        for (FieldError fieldError : result.getFieldErrors()) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return R.error(ExceptionEnum.VALID_EXCEPTION).data("data",map);
    }

    @ExceptionHandler(value = BindException.class)
    public R validException(BindException e){
        log.error("数据校验出现异常{}，异常的类型是{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        for (FieldError fieldError : result.getFieldErrors()) {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return R.error(ExceptionEnum.VALID_EXCEPTION).data("data",map);
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable t){
        log.debug("程序出现异常:",t);
        return R.error(ExceptionEnum.UNKNOW_EXCEPTION);
    }
}
